
	function logOut() {
		dropTimelineTable();	
		air.EncryptedLocalStore.reset();
		document.getElementById('application').src = 'login.html';
		document.getElementById('bottomBar').style.visibility = 'hidden';
		document.getElementById('logout').style.visibility = 'hidden';
//TAE 2008.08.18 (start
		document.getElementById('refresh').style.visibility = 'hidden';
//TAE 2008.08.17 (end
	}

	function initialize(){
		var username = air.EncryptedLocalStore.getItem("username");
		var username_identica = air.EncryptedLocalStore.getItem("username_identica");
		if (username || username_identica) { 
			dropTimelineTable();
			createTimelineTable();
			document.getElementById('application').src = 'messages.html';
			document.getElementById('bottomBar').style.visibility = 'visible';
			document.getElementById('logout').style.visibility = 'visible';
//TAE 2008.08.17 (start
			document.getElementById('refresh').style.visibility = 'visible';
//TAE 2008.08.17 (end		
		} else {
			document.getElementById('application').src = 'login.html';
		}
		
		var topBar = document.getElementById("topBar");
		topBar.addEventListener("mousedown",onMove,true);

		var resizeGripper = document.getElementById("bottom_right");
		resizeGripper.addEventListener("mousedown",onResize,true);
				
		nativeWindow.addEventListener(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, 
									  onDisplayStateChange);

/*** TAE 2008.08.17 (START
  ***  Prefer to use my IconTray Class instread....
		var iconLoadComplete = function(event)
	    {
	        air.NativeApplication.nativeApplication.icon.bitmaps = new runtime.Array(event.target.content.bitmapData);
	    }

	    var iconLoad = new air.Loader();
	    var iconMenu = new air.NativeMenu();
	    var exitCommand = iconMenu.addItem(new air.NativeMenuItem("Exit"));
	    exitCommand.addEventListener(air.Event.SELECT,function(event){
	            air.NativeApplication.nativeApplication.icon.bitmaps = [];
	            air.NativeApplication.nativeApplication.exit();
	    });
//TAE 2008.08.17 (start
	    if (air.NativeApplication.supportsSystemTrayIcon) {
	        air.NativeApplication.nativeApplication.autoExit = false;
	        iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE,iconLoadComplete);
	        iconLoad.load(new air.URLRequest("icons/icon16.png"));
	        air.NativeApplication.nativeApplication.icon.tooltip = "Twitch";
	        air.NativeApplication.nativeApplication.icon.menu = iconMenu;
	    }
//TAE 2008.08.17 (end
	    if (air.NativeApplication.supportsDockIcon) {
	        iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE,iconLoadComplete);
	        iconLoad.load(new air.URLRequest("icons/icon48.png"));
	        air.NativeApplication.nativeApplication.icon.menu = iconMenu;
	    }
**/
	IconTray.getDefault().init();

	window.nativeWindow.addEventListener(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGE, IconTray.getDefault().minimizeToTray);
	window.nativeWindow.addEventListener(air.Event.CLOSING, IconTray.getDefault().close);
	
	//Not required pop-up windows for login/password
	setHandleHTTPAuth(false);
//TAE 2008.08.17 (end

	//TAE 2008.09.06 (start
	document.getElementById('logo').title = "::" + IconTray.getDefault().getDesc();
	Bridge.setToolTips();
	//TAE 2008.09.06 (end
	}
	
	function onClose(){
		var closing = new air.Event(air.Event.CLOSING, true, true);
		window.nativeWindow.dispatchEvent(closing);
		
		/** TAE 2008.09.06 
		  **
		if(!closing.isDefaultPrevented()){
			window.close();
		}
		**/
	}
	
	function onMinimize(){
//TAE 2008.08.17 (start
/**
		var minimizing = 
			new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,
         									  true, true,
           									  window.nativeWindow.displayState,
           									  air.NativeWindowDisplayState.MINIMIZED);
		window.nativeWindow.dispatchEvent(minimizing);
		if(!minimizing.isDefaultPrevented()){		
			nativeWindow.minimize();
		}
**/
		var e = new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,
         									  true, true,
           									  window.nativeWindow.displayState,
           									  air.NativeWindowDisplayState.MINIMIZED);
		IconTray.getDefault().minimizeToTray(e);
//TAE 2008.08.17 (end
	}
	
	function onMaximize(){
		var maximizing =  
			new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,
         									  true, true,
           									  window.nativeWindow.displayState,
           									  air.NativeWindowDisplayState.MAXIMIZED);
		window.nativeWindow.dispatchEvent(maximizing);
		if(!maximizing.isDefaultPrevented()){
			nativeWindow.maximize();
		}
	}

	function onRestore(){
		var restoring =  
			new air.NativeWindowDisplayStateEvent(air.NativeWindowDisplayStateEvent.DISPLAY_STATE_CHANGING,
         									  true, true,
           									  window.nativeWindow.displayState,
           									  air.NativeWindowDisplayState.NORMAL);
		window.nativeWindow.dispatchEvent(restoring);
		if(!restoring.isDefaultPrevented()){
			nativeWindow.restore();
		}
	}	
	
	function onDisplayStateChange(event){
		return;
	}
	
	var onMove = function(event){
		nativeWindow.startMove();
	}

	var onResize = function(event){
		nativeWindow.startResize(air.NativeWindowResize.BOTTOM_RIGHT);
	}
	
//TAE 2008.08.17 (START
	function limitText(limitField, limitCount, limitNum) {
		if (limitField.value.length > limitNum) {
			limitField.value = limitField.value.substring(0, limitNum);
		} else {
			limitCount.value = limitNum - limitField.value.length;
		}
	}
//TAE 2008.08.17 (END

//TAE 2008.08.18 (START
	function reFresh() {
		dump('refresh timeline...');
		var childInterface = document.getElementById("application").contentWindow.childSandboxBridge; 
		var username = air.EncryptedLocalStore.getItem("username");
		var username_identica = air.EncryptedLocalStore.getItem("username_identica");
		
		if (username) {
			updateTimelineSQL();
			updateRepliesTimelineSQL();
			updateDMTimelineSQL();
		}
		if (username_identica) {
			updateTimelineSQL_identica();
			updateRepliesTimelineSQL_identica();
		}
	}
//TAE 2008.08.18 (END

//TAE 2008.08.22 (START
function hiddenShortenURL() {
	document.getElementById('snurlui').style.display = 'none';
	document.getElementById('status').focus();
}

function makeShorten() {
	var txt = document.getElementById('snurlurl');
	var sl = txt.value;
	if(!sl.length) {
		return;
	}
	
	callbackTinyURL(sl);
	hiddenShortenURL();
}
//TAE 2008.08.22 (END

//TAE 2008.08.26 (START
//TwitPIC Post...Thanks to @spaz!
function init_post_pic() {
	var target = document.getElementById('pic_container');
	
	target.addEventListener("dragenter", dragEnterOverHandler);
	target.addEventListener("dragover", dragEnterOverHandler);
	target.addEventListener("drop", dropHandler);
	
	//Default Images
	document.getElementById('pic_container').innerHTML	= '<img src="images/imagedrop.png" />';
}

function destroy_post_pic() {

	var target = document.getElementById('pic_container');

	target.removeEventListener("dragenter", dragEnterOverHandler);
	target.removeEventListener("dragover", dragEnterOverHandler);
	target.removeEventListener("drop", dropHandler);
	
	document.getElementById('fileName').innerHTML = ' ';
}

function dragEnterOverHandler(event) {
    event.preventDefault();
}    

function dropHandler(event) {
	event.preventDefault();
	uploadDraggedImage(event);
}

function post_image() {
	//Validate
	//TAE 2008.09.10 (START --> Enhance Issue#8
	var isWeb = false;
	//TAE 2008.09.10 (end  --> Enhance Issue#8
	
	var fileUrl = document.getElementById('fileName').innerHTML;
	if(!fileUrl.length)
		return;
	
	//TAE 2008.09.10 (START --> Enhance Issue#8
	if(fileUrl.match(/(ftp|http|https):\/\//ig)) {
		isWeb = true;
		//Save locally a resource from web (START
		//Thanks you to http://corlan.org/2008/07/18/air-how-to-save-locally-a-resource-from-web/
		var loader = new air.URLLoader();
		
		loader.dataFormat = air.URLLoaderDataFormat.BINARY;
         
		//attach the event listeneri for load event and errors event
        loader.addEventListener(air.Event.COMPLETE, my_onLoad);
        loader.addEventListener(air.IOErrorEvent.IO_ERROR, my_onError);
        loader.addEventListener(air.SecurityErrorEvent.SECURITY_ERROR, my_onError);
		loader.load(new air.URLRequest(fileUrl));
		//Save locally a resource from web (END
	} else
		uploadImage(fileUrl);
	//TAE 2008.09.10 (END --> Enhance Issue#8
	
	//Save locally a resource from web (START
	function my_onLoad(e) {
	        var fileName = "foo.png";
            //call the saveLocally function; loader.data has the bytes of the loaded resource
            saveLocally(fileName, loader.data);
	}
	
	function my_onError(e) {
		dump('save locally resource error: ' + e);
    } 
	
	function saveLocally(fileName, data) {
            //create a file under the application storage directory using the filename argument
            var file = air.File.applicationStorageDirectory.resolvePath(fileName);
            if (file.exists)
                file.deleteFile(); //delete it if exists
            
			//create a file stream to be able to write the content of the file    
            var fileStream = new air.FileStream();
			
            //open the file stream and set for Write
            fileStream.open(file, air.FileMode.WRITE);
            
			//writes the bytes
            fileStream.writeBytes(data, 0, data.length);
            
			//close the stream
            fileStream.close();

			//Save file name 
			fileUrl = file.nativePath;
			dump('Locally file -> ' + fileUrl);
			
			//Upload
			uploadImage(fileUrl);
    }
	//Save locally a resource from web (END
}

//TAE 2008.09.10 (START
function uploadImage(fileUrl) {
	// upload the file
	uploadFile({
		'extra'  :{
			"username": Bridge.getUsername(),
			"password": Bridge.getPassword(),
			"source":	"Twitch",
		},
		'url'    :"http://twitpic.com/api/upload",
		'fileUrl':fileUrl,
		'open'   : function(event) {
			showStatus('Uploading image to Twitpic...', true);
		},
		'complete': function(event) {
			showStatus('Posts image to Twitpic...', true);

			var loader = event.target;
			dump(loader.data);

			var parser=new DOMParser();
			xmldoc = parser.parseFromString(loader.data,"text/xml");
			
			//var mediaurl = $(xmldoc).find('mediaurl').text();
			var mediaurl = xmldoc.getElementsByTagName('rsp')[0].getElementsByTagName('mediaurl')[0].childNodes(0).nodeValue;
			
			dump(mediaurl);
			
			//Spaz.UI.prepPhotoPost(mediaurl);
			var status = document.getElementById('status').value;
			document.getElementById('status').value = status + ' ' + mediaurl;
			hiddenUploadPic();
		},
	});
}
//TAE 2008.09.10 (END

function uploadDraggedImage(event) {
	//TAE 2008.08.26 (Start
	try {
		var fo = event.dataTransfer.getData("application/x-vnd.adobe.air.file-list");
		var fileUrl = fo[0].nativePath;
	} catch(e) {
		//TAE 2008.09.09 (START
		var fileUrl = event.dataTransfer.getData("text/plain");
		dump(fileUrl);
		//TAE 2008.09.09 (END
	}
	//TAE 2008.08.26 (End
	
	if (fileUrl.match(/^(.+)\.(jpg|jpeg|gif|png)$/i)<1) {
		alert("File must be one of the following:\n .jpg, .jpeg, .gif, .png");
		return;
	}
	
	//Thanks to AlertThngy !	
	var newImage	= document.createElement('IMG');
	newImage.width	= 83;
	
	//TAE 2008.09.09 (START
	if(fileUrl.match(/(ftp|http|https):\/\//ig)) {
		/** New Code for support drag images from web !
		       Need to download image from web to store at local!
		**/
		dump('New Code! ' + fileUrl);	
		document.getElementById('fileName').innerHTML = fileUrl;
		newImage.src	= fileUrl;
	} else {
		var fileUpload	= air.File.applicationStorageDirectory.resolvePath(fileUrl);
		//Upload		
		newImage.src	= fileUpload.url;
		//Show Images
		document.getElementById('fileName').innerHTML = fileUpload.url;
	}
	//TAE 2008.09.09 (END
	
	document.getElementById('pic_container').innerHTML	= '';
	document.getElementById('pic_container').appendChild(newImage);	
}

function uploadFile(opts) {
	var request = new air.URLRequest(opts.url);
	var loader = new air.URLLoader();

	var file = new air.File(opts.fileUrl); //use file.browseForOpen() on ur wish
	var stream = new air.FileStream();
	var buf = new air.ByteArray();

	stream.open(file, air.FileMode.READ);
	stream.readBytes(buf);

	PrepareMultipartRequest(request, buf, 'media', file.nativePath, opts.extra);

	loader.addEventListener(air.Event.COMPLETE, opts.complete);
	loader.addEventListener(air.Event.OPEN, opts.open);
	loader.load(request);

	function PrepareMultipartRequest(request, file_bytes, field_name, native_path, data_before, data_after) {
		var boundary = '---------------------------1076DEAD1076DEAD1076DEAD';
		var header1 = '';
		var header2 = '\r\n';
		var header1_bytes = new air.ByteArray();
		var header2_bytes = new air.ByteArray();
		var body_bytes = new air.ByteArray();
		var n;
		if (!field_name) field_name = 'file';
		if (!native_path) native_path = 'C:\FILE';
		if (!data_before) data_before = {};
		if (!data_after) data_after = {};
		for (n in data_before) {
			header1 += '--' + boundary + '\r\n'
					+ 'Content-Disposition: form-data; name="' + n + '"\r\n\r\n'
					+ data_before[n] + '\r\n';
		}
		header1 += '--' + boundary + '\r\n'
				+ 'Content-Disposition: form-data; name="' + field_name + '"; filename="' + native_path + '"\r\n'
				+ 'Content-Type: application/octet-stream\r\n\r\n';
		for (n in data_after) {
			header2 += '--' + boundary + '\r\n'
					+ 'Content-Disposition: form-data; name="' + n + '"\r\n\r\n'
					+ data_after[n] + '\r\n';
		}
		header2 += '--' + boundary + '--';
		header1_bytes.writeMultiByte(header1, "ascii");
		header2_bytes.writeMultiByte(header2, "ascii");
		body_bytes.writeBytes(header1_bytes, 0, header1_bytes.length);
		body_bytes.writeBytes(file_bytes, 0, file_bytes.length);
		body_bytes.writeBytes(header2_bytes, 0, header2_bytes.length);
		request.method = air.URLRequestMethod.POST;
		request.contentType = 'multipart/form-data; boundary='+boundary;
		request.data = body_bytes;
	}
}
// return;
//TAE 2008.08.26 (END
